package com.kinon.ceshiaccount.sunmi;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.sunmi.bean.HeadBean;
import com.kinon.ceshiaccount.sunmi.bean.ItemBean;
import com.kinon.ceshiaccount.sunmi.bean.KVP;
import com.kinon.ceshiaccount.sunmi.bean.ListingBean;
import com.kinon.ceshiaccount.sunmi.constatus.SunmiImgPath;
import com.kinon.ceshiaccount.sunmi.data.DataModel;
import com.kinon.ceshiaccount.sunmi.data.UPacketFactory;
import com.kinon.ceshiaccount.sunmi.print.AidlUtil;
import com.kinon.ceshiaccount.sunmi.util.SharedPreferencesUtil;
import com.kinon.ceshiaccount.util.BitmapUtils;
import com.kinon.ceshiaccount.util.RegexUtils;
import com.kinon.ceshiaccount.util.SPManage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DataPacket;

/**
 * Created by luohao on 2017-08-02.
 */

public class SunmiSdkManage {
    public static SunmiSdkManage summiManage = null;
    public static DSKernel mDSKernel = null;
    private static HeadBean mHeadBean = null;
    private static Bitmap mT1miniImg = null;
    private Context mContext;

    private SunmiSdkManage() {
        mDSKernel = DSKernel.newInstance();
    }

    public static SunmiSdkManage getInstance() {
        if (summiManage == null || mDSKernel == null) {
            summiManage = new SunmiSdkManage();
        }
        return summiManage;
    }

    public void sunmiInit(Context context, IConnectionCallback mConnCallback) {

        mContext = context;
        mDSKernel.init(context, mConnCallback);
//        mDSKernel.addReceiveCallback(mReceiveCallback);
    }


    public void checkImg(Context context, long fileId, final String key) {

        SunmiSdkManage.mDSKernel.checkFileExist(fileId, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
                Toast.makeText(mContext, "文件不存在", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResult(boolean b) {
                //返回值为true是存在
                //返回值false是不存在
                if (!b) {
                    SharedPreferencesUtil.put(mContext, key, -1L);
                } else {
//                    Toast.makeText(mContext, "文件存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void showWelcomeImg() {
        if (TextUtils.isEmpty(AccountApplication.subModel)) {
            AidlUtil.getInstance().setLCDCommand(4);
//            if(mT1miniImg==null){
//                mT1miniImg=BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.sunmi);
//            }
//            if(mT1miniImg!=null){
//                Log.e("lh", "showWelcomeImg!=null ");
//                AidlUtil.getInstance().setMiniT1Img(mT1miniImg);
//            }

        } else {
            long taskId = SharedPreferencesUtil.getLong(mContext, SunmiImgPath.WELCOME_IMG_ID);
            if (taskId != -1L) {
                showImgWelcome(taskId);
                return;
            }
            File file = new File(SunmiImgPath.pathwelcom);
            if (!file.exists()) {
                Toast.makeText(mContext, "欢迎图片不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), SunmiImgPath.pathwelcom,
                    new ISendCallback() {
                        @Override
                        public void onSendSuccess(long taskId) {
                            showImgWelcome(taskId);
                            SharedPreferencesUtil.put(mContext, SunmiImgPath.WELCOME_IMG_ID, taskId);
                        }

                        @Override
                        public void onSendFail(int i, String s) {
                        }

                        @Override
                        public void onSendProcess(long totle, long sended) {
                        }
                    }
            );
        }
    }

    private void showImgWelcome(long taskId) {
//        Log.e("lh","showImgWelcome--");
        String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME, "");
        mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json1, taskId, null);
    }

    public void showDoubleLineImg(String topText, String bottomText, ISendCallback callback) {
        if (TextUtils.isEmpty(AccountApplication.subModel)) {
            AidlUtil.getInstance().setMiniT1Img(BitmapUtils.getPaymentBitmap(topText, bottomText));
        } else {
            JSONObject object = new JSONObject();
            try {
                object.put("title",topText);
                object.put("content", bottomText);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            DataPacket dataPacket;
            if (TextUtils.isEmpty(topText)
                    && "7".equals(SPManage.getInstance().getString("screenSize"))) {
                dataPacket = UPacketFactory.buildShowSingleText(DSKernel.getDSDPackageName(),
                        object.toString(), callback);
            } else {
                dataPacket = UPacketFactory.buildShowText(DSKernel.getDSDPackageName(),
                        object.toString(), callback);
            }
            SunmiSdkManage.mDSKernel.sendData(dataPacket);
        }
    }


    public void showPrice(String title, String content, ISendCallback callback) {
        showPrice(1, title, content, callback);
    }

    public void showPrice(int type, String title, String content, ISendCallback callback) {
//        if(!AccountApplication.subModel.equals("t1sub14")
//                || !AccountApplication.subModel.equals("t1sub7")){
        if (TextUtils.isEmpty(AccountApplication.subModel)) {
            if (type == 0) {
                AidlUtil.getInstance().setMiniT1ShowData(addSpace(0, content));
            } else {
                AidlUtil.getInstance().setMiniT1ShowData(addSpace(1, content));
            }

        } else {
            JSONObject object = new JSONObject();
            try {
                object.put("title", title);
                object.put("content", content);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            DataPacket dataPacket = null;
            if (TextUtils.isEmpty(title)
                    && "7".equals(SPManage.getInstance().getString("screenSize"))) {
                dataPacket = UPacketFactory.buildShowSingleText(DSKernel.getDSDPackageName(),
                        object.toString(), callback);
            } else {
                dataPacket = UPacketFactory.buildShowText(DSKernel.getDSDPackageName(),
                        object.toString(), callback);
            }
            SunmiSdkManage.mDSKernel.sendData(dataPacket);
        }
    }

    private String addSpace(int type, String content) {
        int count = 0;
        StringBuilder contentBuilder = new StringBuilder(content);
        if (type == 0) {
            contentBuilder.insert(0, " -");
        } else {
            contentBuilder.insert(0, "  ");
        }
        String[] contents = content.split("");
        for (String s : contents) {
            if (RegexUtils.isNumber(s)) {
                count++;
            }
        }
        for (int i = 0; i < 6 - count; i++) {
            contentBuilder.insert(0, "  ");
        }
        return contentBuilder.toString();
    }

    /**
     * 更具图片路径设置欢迎图片
     */
    public void setWelcomeImg(String imgPath) {
        mDSKernel.sendFile(DSKernel.getDSDPackageName(), imgPath, new ISendCallback() {

            @Override
            public void onSendSuccess(long taskId) {
                SharedPreferencesUtil.put(mContext, SunmiImgPath.WELCOME_IMG_ID, taskId);
                showPicture(taskId);
            }

            @Override
            public void onSendFail(int errorId, String errorInfo) {
            }

            @Override
            public void onSendProcess(long totle, long sended) {
            }
        });

    }

    /**
     * 设置单张图片
     *
     * @param taskId
     */
    public void showPicture(long taskId) {
        //显示图片
        try {
            JSONObject json = new JSONObject();
            json.put("dataModel", "SHOW_IMG_WELCOME");
            json.put("data", "default");
            mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json.toString(), taskId, null);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void showSceerTab(List<ItemBean> list, List<KVP> KVPList,
                             ISendCallback callback) {
        ListingBean listing = new ListingBean(Constant.SHOW_SCREENTAB_TITLE, getTabHead(),
                list, KVPList);
        String json = new Gson().toJson(listing);
        DataPacket dataPacket = UPacketFactory.buildPack(DSKernel.getDSDPackageName(),
                DSData.DataType.DATA, DataModel.TEXT, json, callback);
        SunmiSdkManage.mDSKernel.sendData(dataPacket);
    }

    private HeadBean getTabHead() {
        if (mHeadBean == null) {
            mHeadBean = new HeadBean("序列号", "商品名", "单价", "数量", "小计");
        }
        return mHeadBean;
    }

    /**
     * 清除副屏指定缓存文件
     */
    public void deleteFileExist(long FileID) {
        mDSKernel.deleteFileExist(FileID, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
                Log.d("lh", "onCheckFail: ----------->");
            }

            @Override
            public void onResult(boolean exist) {
                Log.d("lh", "onResult: ---------->" + exist);
            }
        });
    }
}
